package br.com.pheat.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.pheat.beans.Usuario;
import br.com.pheat.dao.UsuarioDAO;

public class UsuarioServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
       
    public UsuarioServlet() {
        super();
    }

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		tratarRequisicao(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		tratarRequisicao(request, response);
	}
	
	protected void tratarRequisicao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		String login = request.getParameter("login");
		String senha = request.getParameter("senha");
		try{
			Usuario usuario = UsuarioDAO.buscarPorUsuarioESenha(login, senha);
			if(usuario == null)
				response.sendRedirect("index.jsp?m=e");
			else {
				session.setAttribute("UsuarioLogado", usuario);
				RequestDispatcher dispatcher = request.getRequestDispatcher("logado.jsp");
				dispatcher.forward(request, response);
			}
		}
		catch(Exception e){
			response.sendRedirect("erro.jsp");
		}
	}
}